import React, {useEffect, useState} from 'react';
import {Layout,Tabs} from "antd";
import {
    Outlet, useLocation, useNavigate
} from "react-router-dom";
import type {TPanes} from "@/store/slice/common";
import {useAppDispatch, useAppTilte} from "@/hooks";
import {addPanes, delPandes, useSelectorCommon} from "@/store/slice/common";

const {Content} = Layout;
const { TabPane } = Tabs;
function IndexContent() {
    const {pathname:key} = useLocation();
    const navigate = useNavigate();
    const titleObj = useAppTilte();
    const {panes} = useSelectorCommon();
    const dispatch = useAppDispatch();
    const {subTitle:title} = useAppTilte();
    useEffect(()=>{
        dispatch(addPanes({
            title,
            key,
            closable:true
        }))
    },[key])
    return (
        <Content style={{margin: '5PX'}}>
            <div className="site-layout-background" style={{padding: 5, height:"100%"}}>

                <Tabs type="editable-card"
                      hideAdd={true}
                      // 切换面板的回调
                      onChange={(activeKey)=>{
                          navigate(activeKey);
                      }}
                      // 当前激活 tab 面板的 key
                      activeKey={key}
                      //新增和删除页签的回调，在 type="editable-card" 时有效
                      onEdit={(actionKey,action )=>{
                          if(action === "remove"){
                              const index = panes.findIndex((v:TPanes)=>v.key === actionKey);
                              if(index>0){
                                  dispatch(delPandes(index));// 删除
                                  // 如果点击的是关闭当前标签（已选中）
                                  if(actionKey === key)
                                      navigate(panes[index-1].key);// 跳转
                              }
                          }
                      }}
                >
                    {panes.map((pane:TPanes) => (
                        <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
                            {
                                key===pane.key && <Outlet/>
                            }
                        </TabPane>
                    ))}
                </Tabs>
            </div>
        </Content>
    );
}

export default IndexContent;